package com.liholin.springboot.sample.configdata

import com.baomidou.mybatisplus.extension.plugins.pagination.Page
import com.liholin.springboot.sample.exception.ErrorStatus
import io.swagger.annotations.ApiModel
import io.swagger.annotations.ApiModelProperty
import lombok.Data
import java.io.Serializable

@ApiModel(value = "全局统一返回结果")
class ResponseData : Serializable {
    @ApiModelProperty(value = "是否成功")
    var success = false

    @ApiModelProperty(value = "返回码")
    var code: Long? = null

    @ApiModelProperty(value = "返回消息")
    var message: String? = null

    @ApiModelProperty(value = "时间戳")
    var ts: Long? = null

    @ApiModelProperty(value = "返回数据")
    var data: Any? = null

    private constructor()
    private constructor(code: Long, msg: String, data: Any?,success : Boolean = true) {
        this.code = code
        message = msg
        this.success = success
        ts = System.currentTimeMillis()
        if (data is Page<*>) {
            val pageData = PageData()
            pageData.total = data.total
            pageData.pageData = data.records
            this.data = pageData
        } else {
            this.data = 0
            this.data = data
        }
    }

    @ApiModel(value = "分页数据显示")
    private class PageData {
        @ApiModelProperty(value = "返回数据")
        var pageData: Any? = null

        @ApiModelProperty(value = "总条数")
        var total: Long? = null
    }

    fun message(message: String?): ResponseData {
        this.message = message
        return this
    }

    fun code(code: Long): ResponseData {
        this.code = code
        return this
    }

    fun data(data: Any?): ResponseData {
        this.data = data
        return this
    }

    companion object {
        const val OK_MSG = "请求成功"
        const val FAIL_MSG = "请求失败"
        fun ok(): ResponseData {
            val r = ResponseData()
            r.success = true
            r.code = ResultCode.OK
            r.message = OK_MSG
            return r
        }

        fun ok(data: Any?): ResponseData {
            return ResponseData(ResultCode.OK, OK_MSG, data)
        }

        fun ok(msg: String, data: Any? = null): ResponseData {
            return ResponseData(ResultCode.OK, msg, data)
        }

        fun error(): ResponseData {
            val r = ResponseData()
            r.success = false
            r.code = ErrorStatus.OPERATION_FAILED.value
            r.message = ErrorStatus.OPERATION_FAILED.errorMessageZh
            return r
        }

        fun error(msg: String,errorStatus : ErrorStatus = ErrorStatus.OPERATION_FAILED): ResponseData {
            return ResponseData(errorStatus.value, msg, null,false)
        }

        fun error(errorStatus : ErrorStatus): ResponseData {
            return ResponseData(errorStatus.value, errorStatus.errorMessageZh, null,false)
        }
    }
}